//#include <stdio.h>
#include <math.h>
#include "user.h"
#include "user_doe.h"

static double R,f,wl,d,s,angle,Cos;
static int sign;
double ContourFun(double ul, double vl) {

float c, ph, ph1, rez;
int id, id1;

c = 2*M_PI/(wl*f);
if( sqrt(ul*ul+vl*vl) <= R)
   {
     ph =(c*.75*d/pow(R,3))*(.5*pow(vl*R,2)-pow(vl,4)/12);
     ph1=(c*.75*d/pow(R,3))*(.5*pow(ul*R,2)-pow(ul,4)/12);
     ph  +=c*(ul+R)*d/2;
     ph1 +=c*(vl+R)*d/2;
     ph   =fmod(ph, 2*M_PI);
     ph1  =fmod(ph1,2*M_PI);
  if( ph <M_PI ) id =1; else id =2;
  if( ph1<M_PI ) id1=3; else id1=4;
 if( (id==1) && (id1==3) ) rez= 7*M_PI/4;
 if( (id==1) && (id1==4) ) rez=   M_PI/4;
 if( (id==2) && (id1==3) ) rez= 5*M_PI/4;
 if( (id==2) && (id1==4) ) rez= 3*M_PI/4;

   }
else  rez = 0;
  if(sign) return rez;
  else     return (rez-c*(ul*ul+vl*vl)/2);

}
double ContourFun1(double ul, double vl) {
return ContourFun(Cos*ul,vl);
}
void ContourMinMax(double *min, double *max) {

if(sign) { *min=M_PI/4; *max=7*(*min);}
else     { *min=-M_PI*R*R/(wl*f)+M_PI/4; *max=7*M_PI/4; }

}

void Contour()   {
   char *InputValues[7];
   char *Title={"Focusator at square contour"};

   char *ParNames[]={
		     "Aperture Radius    :",
		     "Focal    Length    :",
		     "Contour  Size      :",
		     "WaveLength (micron):",
		     "Angle              :",
		     "Discretization Step:",
		     "With Lens/Else  0/1:"
		     };

   char *Default[]={
		    "    6.4          ",
		    "  500.0          ",
		    "    2.0          ",
		    "    1.06         ",
		    "    0.0          ",
		    "    0.1          ",
		    "    1            "
		    };
   if(!sedit(25,5,7,ParNames,InputValues,Default,Title))  return ;

   // read input data
   sscanf(InputValues[0],"%lf",&R);   sprintf(Default[0],"%f",R);
   sscanf(InputValues[1],"%lf",&f);   sprintf(Default[1],"%f",f);
   sscanf(InputValues[2],"%lf",&d);   sprintf(Default[2],"%f",d);
   sscanf(InputValues[3],"%lf",&wl);  sprintf(Default[3],"%f",wl);
   sscanf(InputValues[4],"%lf",&angle);  sprintf(Default[4],"%f",angle);
   Cos=cos(angle*M_PI/180);
   sscanf(InputValues[5],"%lf",&s);   sprintf(Default[5],"%f",s);
   sscanf(InputValues[6],"%d",&sign); sprintf(Default[6],"%d",sign);
   wl=wl/1000;

   // max&min values of phase in this mask
   double min=0,max=1;
   ContourMinMax(&min, &max);
   NonSymmetricDOE(Phase, max, min, ContourFun1);

   if(MessageSize(2*R/Cos, 2*R, s)) return;

   UndoMenu(2) ;
   MessageName("Square Contour");
   for(int i=0; i<6; i++)
      MessageParam(i+1,"%s%s",ParNames[i],Default[i]);
   MessageOut();

   return;
}
